package com.alipay.rebate.shop.service.customer.impl;

import com.alipay.rebate.shop.constants.JdOrdersConstant;
import com.alipay.rebate.shop.constants.OrdersConstant;
import com.alipay.rebate.shop.constants.PddOrdersConstant;
import com.alipay.rebate.shop.constants.UserIncomeConstant;
import com.alipay.rebate.shop.dao.mapper.*;
import com.alipay.rebate.shop.model.*;
import com.alipay.rebate.shop.pojo.order.FindOrdersReq;
import com.alipay.rebate.shop.pojo.user.customer.OrdersListResponse;
import com.alipay.rebate.shop.pojo.userincome.IncomeSchedulerRsp;
import com.alipay.rebate.shop.scheduler.orderimport.AdminImportOrders;
import com.alipay.rebate.shop.service.customer.CustomerOrdersService;
import com.alipay.rebate.shop.utils.DateUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class CustomerOrdersServiceImpl implements CustomerOrdersService {

  private Logger logger = LoggerFactory.getLogger(CustomerOrdersServiceImpl.class);

  @Autowired
  private UserMapper userMapper;
  @Resource
  private OrdersMapper ordersMapper;
  @Resource
  private PddOrdersMapper pddOrdersMapper;
  @Resource
  private UserJdPidMapper userJdPidMapper;
  @Resource
  UserIncomeMapper userIncomeMapper;
  @Resource
  CommissionFreezeLevelSettingsMapper freezeLevelSettingsMapper;
  @Autowired
  private JdOrdersMapper jdOrdersMapper;
  @Resource
  private AdminImportOrders importOrders;
  @Resource
  private BrowseProductMapper browseProductMapper;
  @Resource
  private ActivityBrowseProductMapper activityBrowseProductMapper;
  @Resource
  private MeituanOrdersMapper meituanOrdersMapper;
  @Override
  public Orders get(String id) {
    return ordersMapper.selectByPrimaryKey(id);
  }

  @Override
  public int delete(String id) {
    return ordersMapper.deleteByPrimaryKey(id);
  }

  @Override
  @Transactional
  public PageInfo<OrdersListResponse> selectUserOrdersByType(
      Long tkStatus,
      Integer pageNo,
      Integer pageSize,
      Long userId
  ) {

    List<IncomeSchedulerRsp> freezeIncomes;
    // 查询冻结中的收益记录
    freezeIncomes = userIncomeMapper.selectFreezeIncomeByUserId(userId);
    List<IncomeSchedulerRsp> taobaoFreezeIncomes = new ArrayList<>();
    for (IncomeSchedulerRsp income : freezeIncomes) {
      // 淘宝订单的冻结记录
      if (income.getType() == 1) {
        taobaoFreezeIncomes.add(income);
      }
    }


    User user = userMapper.selectById(userId);
    pageNo = pageNo == null ? 1 : pageNo;
    pageSize = pageSize == null ? 20: pageSize;
    logger.debug("pageNo and pageSize is : {}, {}",pageNo,pageSize);
    PageHelper.startPage(pageNo, pageSize);
    List<OrdersListResponse> page = ordersMapper.selectUserOrdersByType(tkStatus,userId,user.getRelationId());

    setUnfreezingDate(taobaoFreezeIncomes,page,UserIncomeConstant.FREEZING_TYPE);
    setPaidStatus(page);
    logger.debug("ordersListResponses is : {}",page);
    logger.debug("page is : {}", page);
    PageInfo<OrdersListResponse> pageInfo = new PageInfo<>(page);
    logger.debug("pageInfo is:{}", pageInfo);
    return pageInfo;
  }

  @Override
  public PageInfo<OrdersListResponse> selectFansOrdersByType(
      Long tkStatus,
      Integer pageNo,
      Integer pageSize,
      Long userId) {
    pageNo = pageNo == null ? 1 : pageNo;
    pageSize = pageSize == null ? 20: pageSize;
    List<Long> fansIds = userMapper.selectOneLevelFansIds(userId);
    logger.debug("oneLevelFansIds is : {}",fansIds);
    List<OrdersListResponse> ordersLists = new ArrayList<>();

    if(fansIds.size() > 0) {
      List<Long> secondLevelFansIds = userMapper.selectSecondLevelFansIds(fansIds);
      logger.debug("secondLevelFansIds is : {}",secondLevelFansIds);
      if(secondLevelFansIds.size() > 0 ){
        fansIds.addAll(secondLevelFansIds);
      }
      logger.debug("fansIds is : {}",fansIds);
      PageHelper.startPage(pageNo,pageSize);

      ordersLists = ordersMapper.selectFansOrdersByType(tkStatus,fansIds);

      setPrivacyProtection(fansIds,ordersLists);

      List<IncomeSchedulerRsp> freezeIncomes;
      // 查询冻结中的收益记录
      freezeIncomes = userIncomeMapper.selectFansFreezeIncomeByUserId(fansIds);
      logger.debug("freezeIncomes is : {}",freezeIncomes);
      List<IncomeSchedulerRsp> taobaoFreezeIncomes = new ArrayList<>();
      for (IncomeSchedulerRsp income : freezeIncomes) {
        // 淘宝订单的冻结记录
        if (income.getType() == 1) {
          taobaoFreezeIncomes.add(income);
        }
      }
      setUnfreezingDate(taobaoFreezeIncomes,ordersLists,UserIncomeConstant.FREEZING_TYPE);

      for (OrdersListResponse response : ordersLists){
        String tradeId = response.getTradeId();
        Orders orders = ordersMapper.selectOrdersByTradeId(tradeId);
        response.setUserUit(orders.getOneLevelUserUit());
        if (secondLevelFansIds.size()>0){
          for (Long second : secondLevelFansIds){
            logger.debug("userId is : {},{}",second,response.getUserId());
            logger.debug("second == response.getUserId() is L {}",second == response.getUserId());
            if (response.getUserId() != null) {
              if (second.compareTo(response.getUserId()) == 0) {
                response.setUserUit(orders.getTwoLevelUserUit());
                logger.debug("userUit is : {}", response.getUserUit());
              }
            }
          }
        }
      }


      setPaidStatus(ordersLists);
    }
    logger.debug("ordersList is : {}",ordersLists);

    PageInfo<OrdersListResponse> pageInfo = new PageInfo<>(ordersLists);

    logger.debug("pageInfo is : {}",pageInfo);
    return pageInfo;
  }

  @Override
  public List<Orders> findOrder(FindOrdersReq req) {
    logger.debug("req is : {}",req);
    List<Orders> ordersList1 = ordersMapper.selectOrdersByTradeParentId(req.getId());
    logger.debug("ordersList1 is : {}",ordersList1);
    User user = userMapper.selectById(req.getUserId());
    User parentUser = userMapper.selectById(user.getParentUserId());
    for (Orders orders : ordersList1) {
      // 根据淘宝后六位查询用户
      String taobaoUserIdFinalSixNumber = getTaobaoUserIdFinalSixNumber(req.getId());
      logger.debug("taobaoUserIdFinalSixNumber is : {}",taobaoUserIdFinalSixNumber);
      List<User> users = userMapper.selectUserByTaoBaoUserIdFinalSixNumber(taobaoUserIdFinalSixNumber);
      logger.debug("users is : {}",users);
      if (users.size() < 1){
        // 查询商品浏览记录
        List<BrowseProduct> browseProducts = browseProductMapper.selectBrowseProductByUserIdAndGoodsId(req.getUserId(), orders.getNumIid());
        if (browseProducts != null || browseProducts.size() > 0){
          logger.debug("activityBrowseProductById > 0");
          orders.setIsRecord(2);
          orders.setPromoterId(req.getUserId());
          orders.setPromoterName(user.getUserNickName());
          Orders orders1 = ordersMapper.selectOrdersByTradeId(orders.getTradeId());
          orders1.setTkStatus(0L);
          logger.debug("orders is : {}",orders);
          importOrders.handleOrdersByStatus(orders,orders1,user,parentUser);
        }
      }
      if (users.size() > 0){
        if (user.getUserId() == req.getUserId()) {
          logger.debug("users size > 0");
          orders.setPromoterId(req.getUserId());
          orders.setIsRecord(2);
          orders.setPromoterName(user.getUserNickName());
          Orders orders1 = ordersMapper.selectOrdersByTradeId(orders.getTradeId());
          orders1.setTkStatus(0L);
          logger.debug("orders is : {}", orders);
          importOrders.handleOrdersByStatus(orders, orders1, user, parentUser);
        }
      }
    }
    return ordersList1;
  }
  private String getTaobaoUserIdFinalSixNumber(String tradeIdStr){
    Integer length = tradeIdStr.length();
    StringBuilder builder = new StringBuilder();
    builder.append(tradeIdStr.substring(length -6,length - 4));
    builder.append(tradeIdStr.substring(length -2,length));
    builder.append(tradeIdStr.substring(length -4,length - 2));
    return builder.toString();
  }

  private void setPaidStatus(List<OrdersListResponse> ordersLists){
    if(ordersLists!=null && ordersLists.size() >0){
      ordersLists.stream().forEach(ordersListResponse -> {
        ordersListResponse.setIsPaid(UserIncomeConstant.IS_PAID);
        if(unPaid(ordersListResponse.getTkStatus())){
          ordersListResponse.setIsPaid(UserIncomeConstant.UN_PAID);
        }
      });
    }
  }

  private boolean unPaid(Long tkStatus){
    if(tkStatus == OrdersConstant.PAID_STATUS
        || tkStatus == OrdersConstant.OVERDUE_STATUS){
      return true;
    }
    return false;
  }

  private void setPddOrderPaidStatus(List<OrdersListResponse> ordersLists){
    if(ordersLists!=null && ordersLists.size() >0){
      ordersLists.stream().forEach(ordersListResponse -> {
        ordersListResponse.setIsPaid(UserIncomeConstant.IS_PAID);
        if(PddUnPaid(ordersListResponse.getTkStatus())){
          ordersListResponse.setIsPaid(UserIncomeConstant.UN_PAID);
        }
      });
    }
  }

  private void setJdOrderPaidStatus(List<OrdersListResponse> ordersLists){
    if(ordersLists!=null && ordersLists.size() >0){
      ordersLists.stream().forEach(ordersListResponse -> {
        ordersListResponse.setIsPaid(UserIncomeConstant.IS_PAID);
        if(JdUnPaid(ordersListResponse.getTkStatus())){
          ordersListResponse.setIsPaid(UserIncomeConstant.UN_PAID);
        }
      });
    }
  }

  private boolean PddUnPaid(Long tkStatus){
    if(tkStatus == PddOrdersConstant.PDD_ACCOUNTING_STATUS.longValue()){
      return true;
    }
    return false;
  }

  private boolean JdUnPaid(Long tkStatus){
    if(tkStatus == JdOrdersConstant.JD_ACCOUNTING_STATUS.longValue()){
      return true;
    }
    return false;
  }


  @Override
  public List<Orders> selectOrderByGoodIdAndOrderType(String goodId, String orderType) {
    return ordersMapper.selectOrderByGoodIdAndOrderType(goodId,orderType);
  }


  //查询我的订单，包括淘宝订单，拼多多订单
  @Override
  public PageInfo<OrdersListResponse> selectUserOrdersByTypeTwo(Long tkStatus, Integer type, Integer pageNo,
                                                                Integer pageSize, Long userId) {

    List<IncomeSchedulerRsp> freezeIncomes;
    // 查询冻结中的收益记录
    freezeIncomes = userIncomeMapper.selectFreezeIncomeByUserId(userId);
    List<IncomeSchedulerRsp> taobaoFreezeIncomes = new ArrayList<>();
    if (type == null || type == 1){
      PageInfo<OrdersListResponse> pageInfo =
              selectUserTaobaoOrders(freezeIncomes, userId, pageNo, pageSize, tkStatus, taobaoFreezeIncomes);
      return pageInfo;
    }
    if (type == 2){
      PageInfo<OrdersListResponse> pageInfo =
              selectUserPddOrders(freezeIncomes, userId, pageNo, pageSize, tkStatus, taobaoFreezeIncomes);
      return pageInfo;
    }
    if (type == 3){
      PageInfo<OrdersListResponse> pageInfo =
              selectUserJdOrders(freezeIncomes, userId, pageNo, pageSize, tkStatus, taobaoFreezeIncomes);
      return pageInfo;
    }
    if (type == 4){
      PageInfo<OrdersListResponse> pageInfo = selectUserMeituanOrders(userId, pageNo, pageSize);
      return pageInfo;
    }
    return null;
  }

  private PageInfo<OrdersListResponse> selectUserMeituanOrders(Long userId, Integer pageNo,Integer pageSize){
    User user = userMapper.selectById(userId);
    pageNo = pageNo == null ? 1 : pageNo;
    pageSize = pageSize == null ? 20: pageSize;
    logger.debug("pageNo and pageSize is : {}, {}",pageNo,pageSize);
    PageHelper.startPage(pageNo, pageSize);
    List<OrdersListResponse> page = meituanOrdersMapper.selectMeituanOrdersByUserId(userId);
    setPaidStatus(page);
    logger.debug("ordersListResponses is : {}",page);
    logger.debug("page is : {}", page);
    PageInfo<OrdersListResponse> pageInfo = new PageInfo<>(page);
    logger.debug("pageInfo is:{}", pageInfo);
    return pageInfo;
  }

  private PageInfo<OrdersListResponse> selectUserTaobaoOrders(List<IncomeSchedulerRsp> freezeIncomes,Long userId,
                                                              Integer pageNo,Integer pageSize,Long tkStatus,
                                                              List<IncomeSchedulerRsp> taobaoFreezeIncomes){
    for (IncomeSchedulerRsp income : freezeIncomes) {
      // 淘宝订单的冻结记录
      if (income.getType() == 1) {
        taobaoFreezeIncomes.add(income);
      }
    }

    User user = userMapper.selectById(userId);
    pageNo = pageNo == null ? 1 : pageNo;
    pageSize = pageSize == null ? 20: pageSize;
    logger.debug("pageNo and pageSize is : {}, {}",pageNo,pageSize);
    PageHelper.startPage(pageNo, pageSize);
    //淘宝订单
    List<OrdersListResponse> page = ordersMapper.selectUserOrdersByType(tkStatus,userId,user.getRelationId());

    setUnfreezingDate(taobaoFreezeIncomes,page,UserIncomeConstant.FREEZING_TYPE);
    setPaidStatus(page);
    logger.debug("ordersListResponses is : {}",page);
    logger.debug("page is : {}", page);
    PageInfo<OrdersListResponse> pageInfo = new PageInfo<>(page);
    logger.debug("pageInfo is:{}", pageInfo);
    return pageInfo;

  }
  private PageInfo<OrdersListResponse> selectUserJdOrders(List<IncomeSchedulerRsp> freezeIncomes,Long userId,
                                                          Integer pageNo,Integer pageSize,Long tkStatus,
                                                          List<IncomeSchedulerRsp> taobaoFreezeIncomes){
    for (IncomeSchedulerRsp income : freezeIncomes) {
      // 京东订单的冻结记录
      if (income.getType() == 17) {
        taobaoFreezeIncomes.add(income);
      }
    }

    //京东订单
    UserJdPid userJdPid = userJdPidMapper.selectUserJdPidByUserId(userId);
    pageNo = pageNo == null ? 1 : pageNo;
    pageSize = pageSize == null ? 20: pageSize;
    logger.debug("pageNo and pageSize is : {}, {}",pageNo,pageSize);

    PageHelper.startPage(pageNo, pageSize);
    logger.debug("userId is : {}",userId);
    logger.debug("pid is : {}",userJdPid);
    Long validCode = null;
    if (tkStatus != null){
      validCode = tkStatus;
    }

    List<OrdersListResponse> ordersListResponses = jdOrdersMapper.selectJdOrdersByStatus(validCode, userId);
    setUnfreezingDate(taobaoFreezeIncomes,ordersListResponses,UserIncomeConstant.FREEZING_JD_TYPE);
    setJdOrderPaidStatus(ordersListResponses);
    logger.debug("pddOrdersListRes is : {}",ordersListResponses);
    PageInfo<OrdersListResponse> pageInfo = new PageInfo<>(ordersListResponses);
    return pageInfo;
  }
  private PageInfo<OrdersListResponse> selectUserPddOrders(List<IncomeSchedulerRsp> freezeIncomes,Long userId,
                                                           Integer pageNo,Integer pageSize,Long tkStatus,
                                                           List<IncomeSchedulerRsp> taobaoFreezeIncomes){
    for (IncomeSchedulerRsp income : freezeIncomes) {
      // 拼多多订单的冻结记录
      if (income.getType() == 16) {
        taobaoFreezeIncomes.add(income);
      }
    }

    //拼多多订单
    String pid = userJdPidMapper.selectUserPddPidByUserId(userId);

    pageNo = pageNo == null ? 1 : pageNo;
    pageSize = pageSize == null ? 20: pageSize;
    logger.debug("pageNo and pageSize is : {}, {}",pageNo,pageSize);

    PageHelper.startPage(pageNo, pageSize);
    logger.debug("userId is : {}",userId);
    logger.debug("pid is : {}",pid);
    Integer ordersStatus = null;
    if (tkStatus != null){
      ordersStatus = tkStatus.intValue();
    }
    List<OrdersListResponse> ordersListResponses = pddOrdersMapper.selectUserOrdersByType(ordersStatus, userId);

    setUnfreezingDate(taobaoFreezeIncomes,ordersListResponses,UserIncomeConstant.FREEZING_PDD_TYPE);
    setPddOrderPaidStatus(ordersListResponses);
    logger.debug("pddOrdersListRes is : {}",ordersListResponses);
    PageInfo<OrdersListResponse> pageInfo = new PageInfo<>(ordersListResponses);
    return pageInfo;
  }


  //查询粉丝订单，包括淘宝订单，拼多多订单
  @Override
  public PageInfo<OrdersListResponse> selectFansOrdersByTypeTwo(Long tkStatus, Integer type,
                                                                Integer pageNo, Integer pageSize, Long userId) {
    logger.debug("type is : {}",type);
    List<Long> fansIds = userMapper.selectOneLevelFansIds(userId);
    logger.debug("fansIds is : {}",fansIds);
    List<OrdersListResponse> ordersLists = new ArrayList<>();
    if(fansIds.size() > 0) {
      List<Long> secondLevelFansIds = userMapper.selectSecondLevelFansIds(fansIds);
      logger.debug("secondLevelFansIds is : {}",secondLevelFansIds);
      if(secondLevelFansIds.size() > 0 ){
        fansIds.addAll(secondLevelFansIds);
      }
      logger.debug("fansIds is : {}",fansIds);
      pageNo = pageNo == null ? 1 : pageNo;
      pageSize = pageSize == null ? 20: pageSize;
      logger.debug("oneLevelFansIds is : {}",fansIds);

      //淘宝粉丝订单
      if (type == null || type == 1){
        PageInfo<OrdersListResponse> pageInfo =
                selectFansTaobaoOrders(pageNo, pageSize, fansIds, tkStatus, secondLevelFansIds, ordersLists);
        return pageInfo;
      }

      if (type == 2){
        PageInfo<OrdersListResponse> pageInfo =
                selectFansPddOrders(pageNo, pageSize, fansIds, tkStatus, secondLevelFansIds, ordersLists);
        return pageInfo;
      }
      if (type == 3){
        PageInfo<OrdersListResponse> pageInfo =
                selectFansJdOrders(pageNo, pageSize, fansIds, tkStatus, secondLevelFansIds, ordersLists);
        return pageInfo;
      }
      if (type == 4){
        PageInfo<OrdersListResponse> pageInfo =
                selectFansMeiTuanOrders(pageNo, pageSize, fansIds, secondLevelFansIds, ordersLists);
        return pageInfo;
      }
    }

    return null;
  }

  private PageInfo<OrdersListResponse> selectFansMeiTuanOrders(Integer pageNo,Integer pageSize, List<Long> fansIds,
                                                               List<Long> secondLevelFansIds,
                                                               List<OrdersListResponse> ordersLists){
    PageHelper.startPage(pageNo,pageSize);
    logger.debug("fansIds is : {}",fansIds);
    List<OrdersListResponse> ordersListResponses = meituanOrdersMapper.selectFansMeituanOrders(fansIds);

    setPrivacyProtection(fansIds,ordersListResponses);

    for (OrdersListResponse response : ordersListResponses){
      String tradeId = response.getTradeId();
      MeituanOrders meituanOrders = meituanOrdersMapper.selectMeituanOrdersByOrderId(tradeId);
      response.setUserUit(meituanOrders.getOneLevelUserUit());
      if (secondLevelFansIds.size()>0){
        for (Long second : secondLevelFansIds){
          logger.debug("userId is : {},{}",second,response.getUserId());
          logger.debug("second == response.getUserId() is L {}",second == response.getUserId());
          if (response.getUserId() != null) {
            if (second.compareTo(meituanOrders.getUserId()) == 0) {
              response.setUserUit(meituanOrders.getTwoLevelUserUit());
              logger.debug("userUit is : {}", response.getUserUit());
            }
          }
        }
      }
    }
    setPaidStatus(ordersLists);
    logger.debug("ordersList is : {}",ordersLists);
    PageInfo<OrdersListResponse> pageInfo = new PageInfo<>(ordersListResponses);
    logger.debug("pageInfo is : {}",pageInfo);
    return pageInfo;
  }

  private PageInfo<OrdersListResponse> selectFansJdOrders(Integer pageNo,Integer pageSize, List<Long> fansIds,
                                                          Long tkStatus, List<Long> secondLevelFansIds,
                                                          List<OrdersListResponse> ordersLists){
    PageHelper.startPage(pageNo,pageSize);
    Long validCode = null;
    if (tkStatus != null){
      validCode = tkStatus;
    }
    logger.debug("fansIds is : {}",fansIds);
    List<OrdersListResponse> ordersListResponses = jdOrdersMapper.selectFansJdOrdersByType(validCode, fansIds);

    setPrivacyProtection(fansIds,ordersListResponses);

    setJdOrderPaidStatus(ordersListResponses);
    List<IncomeSchedulerRsp> freezeIncomes;
    // 查询冻结中的收益记录
    freezeIncomes = userIncomeMapper.selectFansFreezeIncomeByUserId(fansIds);
    logger.debug("freezeIncomes is : {}",freezeIncomes);
    List<IncomeSchedulerRsp> jdFreezeIncomes = new ArrayList<>();
    for (IncomeSchedulerRsp income : freezeIncomes) {
      // 京东订单的冻结记录
      if (income.getType() == 17) {
        jdFreezeIncomes.add(income);
      }
    }
    // 获取佣金冻结等级比例配置
    setUnfreezingDate(jdFreezeIncomes,ordersListResponses,UserIncomeConstant.FREEZING_JD_TYPE);

    for (OrdersListResponse response : ordersListResponses){
      String tradeId = response.getTradeId();
      JdOrders jdOrders = jdOrdersMapper.selectOrderByOrderId(Long.valueOf(tradeId));
      response.setUserUit(jdOrders.getOneLevelUserUit());
      if (secondLevelFansIds.size()>0){
        for (Long second : secondLevelFansIds){
          logger.debug("userId is : {},{}",second,response.getUserId());
          logger.debug("second == response.getUserId() is L {}",second == response.getUserId());
          if (response.getUserId() != null) {
            if (second.compareTo(jdOrders.getUserId()) == 0) {
              response.setUserUit(jdOrders.getTwoLevelUserUit());
              logger.debug("userUit is : {}", response.getUserUit());
            }
          }
        }
      }
    }
    setPaidStatus(ordersLists);
    logger.debug("ordersList is : {}",ordersLists);
    PageInfo<OrdersListResponse> pageInfo = new PageInfo<>(ordersListResponses);
    logger.debug("pageInfo is : {}",pageInfo);
    return pageInfo;
  }
  private PageInfo<OrdersListResponse> selectFansTaobaoOrders(Integer pageNo,Integer pageSize, List<Long> fansIds,
                                                              Long tkStatus, List<Long> secondLevelFansIds,
                                                              List<OrdersListResponse> ordersLists){
    PageHelper.startPage(pageNo,pageSize);
    ordersLists = ordersMapper.selectFansOrdersByType(tkStatus,fansIds);

    setPrivacyProtection(fansIds,ordersLists);

    List<IncomeSchedulerRsp> freezeIncomes;
    // 查询冻结中的收益记录
    freezeIncomes = userIncomeMapper.selectFansFreezeIncomeByUserId(fansIds);
    logger.debug("freezeIncomes is : {}",freezeIncomes);
    List<IncomeSchedulerRsp> taobaoFreezeIncomes = new ArrayList<>();
    for (IncomeSchedulerRsp income : freezeIncomes) {
      // 淘宝订单的冻结记录
      if (income.getType() == 1) {
        taobaoFreezeIncomes.add(income);
      }
    }
    setUnfreezingDate(taobaoFreezeIncomes,ordersLists,UserIncomeConstant.FREEZING_TYPE);

    for (OrdersListResponse response : ordersLists){
      String tradeId = response.getTradeId();
      Orders orders = ordersMapper.selectOrdersByTradeId(tradeId);
      response.setUserUit(orders.getOneLevelUserUit());
      if (secondLevelFansIds.size()>0){
        for (Long second : secondLevelFansIds){
          logger.debug("userId is : {},{}",second,response.getUserId());
          logger.debug("second == response.getUserId() is L {}",second == response.getUserId());
          if (response.getUserId() != null) {
            if (second.compareTo(response.getUserId()) == 0) {
              response.setUserUit(orders.getTwoLevelUserUit());
              logger.debug("userUit is : {}", response.getUserUit());
            }
          }
        }

      }
    }
    setPaidStatus(ordersLists);

    logger.debug("ordersList is : {}",ordersLists);

    PageInfo<OrdersListResponse> pageInfo = new PageInfo<>(ordersLists);

    logger.debug("pageInfo is : {}",pageInfo);
    return pageInfo;

  }
  private PageInfo<OrdersListResponse> selectFansPddOrders(Integer pageNo,Integer pageSize, List<Long> fansIds,
                                                           Long tkStatus, List<Long> secondLevelFansIds,
                                                           List<OrdersListResponse> ordersLists){
    PageHelper.startPage(pageNo,pageSize);

    Integer ordersStatus = null;
    if (tkStatus != null){
      ordersStatus = tkStatus.intValue();
    }
    logger.debug("ordersStatus is : {}",ordersStatus);
    logger.debug("fansIds is : {}",fansIds);
    List<OrdersListResponse> ordersListResponses = pddOrdersMapper.selectFansOrdersByType(ordersStatus,fansIds);

    setPrivacyProtection(fansIds,ordersListResponses);

    setPddOrderPaidStatus(ordersListResponses);
    List<IncomeSchedulerRsp> freezeIncomes;
    // 查询冻结中的收益记录
    freezeIncomes = userIncomeMapper.selectFansFreezeIncomeByUserId(fansIds);
    logger.debug("freezeIncomes is : {}",freezeIncomes);
    List<IncomeSchedulerRsp> pddFreezeIncomes = new ArrayList<>();
    for (IncomeSchedulerRsp income : freezeIncomes) {
      // 拼多多订单的冻结记录
      if (income.getType() == 16) {
        pddFreezeIncomes.add(income);
      }
    }

    setUnfreezingDate(pddFreezeIncomes,ordersListResponses,UserIncomeConstant.FREEZING_PDD_TYPE);

    for (OrdersListResponse response : ordersListResponses){
      String tradeId = response.getTradeId();
      PddOrders pddOrders = pddOrdersMapper.selectPddOrdersByOrderSn(tradeId);
      response.setUserUit(pddOrders.getOneLevelUserUit());
      if (secondLevelFansIds.size()>0){
        for (Long second : secondLevelFansIds){
          logger.debug("userId is : {},{},{}",second,response.getUserId(),pddOrders.getUserId());
          logger.debug("second == response.getUserId() is L {}",second == response.getUserId());
          if (response.getUserId() != null) {
            if (second.compareTo(pddOrders.getUserId()) == 0) {
              response.setUserUit(pddOrders.getTwoLevelUserUit());
              logger.debug("userUit is : {}", response.getUserUit());
            }
          }
        }

      }
    }
    setPaidStatus(ordersLists);
    logger.debug("ordersList is : {}",ordersLists);
    PageInfo<OrdersListResponse> pageInfo = new PageInfo<>(ordersListResponses);
    logger.debug("pageInfo is : {}",pageInfo);
    return pageInfo;
  }

  private Map<String,String> getUnfreezingDateMap(List<CommissionFreezeLevelSettings> levelSettings,
                                                         List<IncomeSchedulerRsp> freezeIncomes){
    Map<String,String> localDateTimeMap = new HashMap<>();
    for (IncomeSchedulerRsp rsp : freezeIncomes){
      String unfreezingDate = getUnfreezingDate(rsp, levelSettings);
      localDateTimeMap.put(rsp.getTradeId(),unfreezingDate);
    }
    return localDateTimeMap;
  }

  // 查看时判断是否到达冻结日期
  private String getUnfreezingDate(IncomeSchedulerRsp userIncome,
                                 List<CommissionFreezeLevelSettings> levelSettings){
    int freezeDay  = 0;
    // 找到冻结天数
    for(CommissionFreezeLevelSettings settings: levelSettings){
      if(settings.getBegin().compareTo(userIncome.getMoney()) <=0 &&
              settings.getEnd().compareTo(userIncome.getMoney()) >0){
        logger.debug("suitable CommissionFreezeLevelSettings is : {}",settings);
        freezeDay = settings.getFreezeDay();
        break;
      }
    }
    // 判断时间是否已经达到冻结天数设置时间
    LocalDateTime paidTimePlus = DateUtil.getLocationDateTime(userIncome.getPaidTime()).plusDays(freezeDay);
    logger.debug("paidTimePlus : {}", paidTimePlus);
    DateTimeFormatter fmtDay = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    String format = paidTimePlus.format(fmtDay);
    return format;
  }

  private void setPrivacyProtection(List<Long> fansIds,List<OrdersListResponse> ordersLists){
    List<User> privacyProtectionByUserId = userMapper.getPrivacyProtectionByUserId(fansIds);
    logger.debug("privacyProtectionByUserId is : {}",privacyProtectionByUserId);
    if (privacyProtectionByUserId.size() > 0) {
      logger.debug("privacyProtectionByUserId is not null");
      for (OrdersListResponse response : ordersLists) {
        for (User user : privacyProtectionByUserId) {
          logger.debug("response.getUserId and user.getUserId is : {},{}",response.getUserId(),user.getUserId());
          if (response.getUserId() != null) {
            if (response.getUserId().compareTo(user.getUserId()) == 0) {
              response.setPrivacyProtection(user.getPrivacyProtection());
              logger.debug("getPrivacyProtection is : {}", response.getPrivacyProtection());
            }
          }
          if (response.getPromoterId() != null) {
            if (response.getPromoterId().compareTo(user.getUserId()) == 0) {
              response.setPrivacyProtection(user.getPrivacyProtection());
              logger.debug("getPrivacyProtection is : {}", response.getPrivacyProtection());
            }
          }
        }
      }
    }
  }

  private void setUnfreezingDate(List<IncomeSchedulerRsp> taobaoFreezeIncomes,List<OrdersListResponse> ordersLists,int type) {
    // 获取佣金冻结等级比例配置
    List<CommissionFreezeLevelSettings> taobaoLevelSettings =
            freezeLevelSettingsMapper.getCommissionFreezeLevelSettingsMapperByType(type);
    Map<String, String> unfreezingDateMap = getUnfreezingDateMap(taobaoLevelSettings, taobaoFreezeIncomes);
    logger.debug("unfreezingDateMap is : {}", unfreezingDateMap);
    for (OrdersListResponse response : ordersLists) {
      for (Map.Entry<String, String> entry : unfreezingDateMap.entrySet()) {
        if (response.getTradeId().equals(entry.getKey())) {
          response.setUnfreezingDate(entry.getValue());
        }
      }
    }
  }

}
